package com.science.slam.utils;

import com.science.slam.exception.BusinessException;
import com.science.slam.exception.ErrorCode;
import org.redisson.Redisson;
import org.redisson.api.RScript;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;


public class IDUtils {
    static {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://localhost:6379");
        config.useSingleServer().setDatabase(0);
        redissonClient = Redisson.create(config);
    }

    private static final RedissonClient redissonClient;
    private static final long epoch = 1727770485078L; // 特定开始时间
    private static final int sequenceBits = 12;

    public static String uniqueFileID() {
        try {
            return uniqueID("file");
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SERVER_ERROR);
        }
    }

    public static String uniqueUserID() {
        try {
            return uniqueID("user");
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SERVER_ERROR);
        }
    }

    public static String uniqueLikeID() {
        try {
            return uniqueID("like");
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SERVER_ERROR);
        }
    }

    private static String uniqueID(String type) throws IOException {
        RScript luaExe = redissonClient.getScript();
        // 后期改为相对路径
        String script = new String(Files.readAllBytes(Paths.get("C:/Users/86183/Desktop/SLAM/src/main/resources/lua/increment.lua")));
        /*
        1. 操作类型
        2. 脚本
        3. 返回类型
        4. keys
        5. params
         */
        Long seq = luaExe.eval(RScript.Mode.READ_WRITE, script, RScript.ReturnType.INTEGER, List.of(type + ":id"));
        long timeStamp = System.currentTimeMillis();
        return ((Long) ((timeStamp << sequenceBits) | seq)).toString();
    }

}

